<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单元素</title>
</head>

<body>
    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        //onChange 不是 input 本身存在的事件, 是 React 定义的事件
        //当 input 元素的值发生改变的时候, 该事件就会触发
        class App extends React.Component {
            //1. 设置状态
            state = {
                username: '',
                password: ''
            }

            render() {
                //获取state中的两个属性
                let { username, password } = this.state;
                return <div className="container">
                    <h2>登录</h2>
                    <form action="">
                        {/*2. 添加value属性 以及 onChange 事件**/}
                        用户名: <input type="text" value={username} name="username" onChange={this.change} /> <br />
                        密码: <input type="text" value={password} name="password" onChange={this.change} /> <br />
                        <button onClick={this.login}>登录</button>
                    </form>
                </div>
            }

            change = (e) => {
                //获取当前input元素对应的属性名
                // let attr = e.target.name;
                let attr = e.target.getAttribute('name');
                this.setState({
                    [attr]: e.target.value
                })
            }



            login = (e) => {
                e.preventDefault()
                //获取用户名和密码的值
                let { username, password } = this.state;
                //输出
                console.log('用户名为: ' + username);
                console.log('密码为: ' + password);
            }
        }

        ReactDOM.render(<App />, document.querySelector("#root"));
    </script>
</body>

</html>